<?php

class Safety_UserController extends App_Controller_Action
{

	public function init()
    {
    	parent::init();    	
    }

    public function indexAction()
    {
        $this->_helper->redirector('read');
    }
    
	/**
	 * This action shows a paginated list of Users
	 */
	public function readAction() 
	{
//		$mainGroups = $this->_entityManager->createQuery('select mg from Model\QualificationMainGroup mg')->getResult();
//		$this->view->mainGroups = $mainGroups;	 
	}
	
	/**
	 * This action is call by the XHR
	 * 
	 * Handles create requests.
	 */
	public function createAction() 
	{ 
		$this->_helper->ajaxContext()->addActionContext('create', 'html')->initContext();
	}
	
	public function createSaveAction() 
	{
		$this->_helper->viewRenderer->setNoRender(true);
        if ($this->_request->isPost()) {
            $form = new Safety_Form_User();
            if ($form->isValid($_POST)) {
                try {
                	// new main group
                    $user = new \model\User();
                	$user->setName($this->_getParam('name',''));
                	$user->setEmail($this->_getParam('email',''));
                	$user->setPw($this->_getParam('pw','123456'));
                	$this->_entityManager->persist($user);
                	$this->_entityManager->flush();
                	// response to client
                	$this->view->success = true;
                    $this->_messenger->addSuccess(_("Their data were processed successfully."));
                    $this->view->message = $this->view->seeMessages();
                } catch (Exception $e) {
                	$this->_logger->err($e->getMessage());
                	// response to client
                	$this->view->success = false;
                    $this->_messenger->addError(_("An error occurred while processing the data. <br/> Please Try again."));
                    $this->view->message = $this->view->seeMessages();
                }
            } else {
            	// response to client
                $this->view->success = false;
            	$this->_messenger->addError(implode("<br/>", $form->getMessages()));
                $this->view->message = $this->view->seeMessages();
            }
        } else {
        	// response to client
        	$this->_messenger->addNotice(_("Data submitted were not processed."));
        	$this->view->success = false;        	
        	$this->view->message = $this->view->seeMessages();
        }
        // send response to client
        $this->_helper->json($this->view);
	}
	
	/**
	 * This action shows the form in edit mode.
	 */
	public function updateAction() 
	{
		$this->_helper->ajaxContext()->addActionContext('update', 'html')->initContext();
        if ($this->_request->isPost()) {
                try {
                	$id = $this->_getParam('id',0);
                	$user = $this->_entityManager->find('model\User', $id);
                	if ($user) {
                		// response to client
	                	$this->view->user = $user;
                	} else {
                		// response to client
	                	$this->view->success = false;
	                    $this->_messenger->addSuccess(_("The requested record was not found."));
	                    $this->view->message = $this->view->seeMessages();
	                    $this->_helper->json($this->view);
                	}
                } catch (Exception $e) {
                	$this->_logger->err($e->getMessage());
                	// response to client
                	$this->view->success = false;
                    $this->_messenger->addError(_("An error occurred while processing the data. <br/> Please Try again."));
                    $this->view->message = $this->view->seeMessages();
                    $this->_helper->json($this->view);
                }
        }
	}
	
	/**
	 *  This action is called by the XhrForm decorator.
	 *  
	 *   Handles update requests.
	 */
	public function updateSaveAction() 
	{
		$this->_helper->viewRenderer->setNoRender(true);
        if ($this->_request->isPost()) {
            $form = new Safety_Form_User();
            if ($form->isValid($_POST)) {
                try {
                	// update main group
                	$id = $this->_getParam('id',0);
                	$user = $this->_entityManager->find('model\User', $id);
                	$user->setName($this->_getParam('name'));
                	$user->setEmail($this->_getParam('email'));
                	$user->setPw($this->_getParam('pw'));
                	$this->_entityManager->persist($user);
                	$this->_entityManager->flush();
                	
                	// response to client
                	$this->view->success = true;
                    $this->_messenger->addSuccess(_("Their data were processed successfully."));
                    $this->view->message = $this->view->seeMessages();
                } catch (Exception $e) {
                	$this->_logger->err($e->getMessage());
                	// response to client
                	$this->view->success = false;
                    $this->_messenger->addError(_("An error occurred while processing the data. <br/> Please Try again."));
                    $this->view->message = $this->view->seeMessages();
                }
            } else {
            	// response to client
                $this->view->success = false;
            	$this->_messenger->addError(implode("<br/>", $form->getMessages()));
                $this->view->message = $this->view->seeMessages();
            }
        } else {
        	// response to client
        	$this->_messenger->addNotice(_("Data submitted were not processed."));
        	$this->view->success = false;        	
        	$this->view->message = $this->view->seeMessages();
        }
        // send response to client
        $this->_helper->json($this->view);
	}
	
	/**
	 * This is action is an XHR action
	 * 
	 *  When requested it will delete Users with the ids found in the payload array.
	 */
	public function deleteAction() 
	{
		$this->_helper->viewRenderer->setNoRender(true);
        if ($this->_request->isPost()) {
            $options = $this->_getParam('users',array());
            if ( !empty($options) ) {
                try {
                	$userRepository = $this->_entityManager->getRepository('model\User');
                	$userRepository->deleteItems($options);                	
                	// response to client
                	$this->view->success = true;
                    $this->_messenger->addSuccess(_("Their data were processed successfully."));
                    $this->view->message = $this->view->seeMessages();
                } catch (Exception $e) {
                	$this->_logger->err($e->getMessage());
                	// response to client
                	$this->view->success = false;
                    $this->_messenger->addError(_("An error occurred while processing the data. <br/> Please Try again."));
                    $this->view->message = $this->view->seeMessages();
                    $this->_helper->json($this->view);
                }
            } else {
            	// response to client
                $this->view->success = false;
            	$this->_messenger->addNotice(_("Data submitted is empty."));
                $this->view->message = $this->view->seeMessages();
            }
        } else {
        	// response to client
        	$this->_messenger->addNotice(_("Data submitted were not processed."));
        	$this->view->success = false;        	
        	$this->view->message = $this->view->seeMessages();
        	$this->_helper->json($this->view);
        }
        // send response to client
        $this->_helper->json($this->view);
	}
	
	/**
	 * 
	 */
	public function readItemsAction() {
//		$this->_helper->viewRenderer->setNoRender();
//		$m = new \model\QualificationMainGroup();
		$query = $this->_entityManager->createQuery('select u from \model\User u');
		
		//paginacion
		$adapter = new App_Paginator_Adapter_Doctrine($query);
		$paginator = new Zend_Paginator($adapter);
		
		$start = $this->_getParam('iDisplayStart', 0);
        $limit = $this->_getParam('iDisplayLength', 10);
        $page = ($start + $limit) / $limit;
        // show page
		$paginator->setCurrentPageNumber($page);
		// show n items by page
		$paginator->setItemCountPerPage($limit);
		
		// output
		$this->view->sEcho = intval($_GET['sEcho']);
		$this->view->iTotalRecords = $paginator->getTotalItemCount();
		$this->view->iTotalDisplayRecords = $paginator->getTotalItemCount();
		$this->view->aaData = array();
		foreach ($paginator as $t) {
			$row = array();
			$row[] = $t->getId();
			$row[] = $t->getName();
			$row[] = $t->getEmail();
			
			$this->view->aaData[] = $row;
		}
		$this->_helper->json($this->view);
	}
}

